package com.ruoyi.common.utils.shell;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * shell执行
 *
 * @author Hack2003
 * @date 2024/3/26 10:57
 **/
@Slf4j
public class ShellUtil {

    /**
     * 拼接数组
     * @param base 基础数组
     * @param add 添加数组
     * @return
     */
    public static String[] arrAddEnd(String[] base, String[] add){
        String[] cmd = new String[base.length + add.length];
        System.arraycopy(base, 0, cmd, 0, base.length);
        System.arraycopy(add, 0, cmd, base.length, add.length);
        return cmd;
    }
    /**
     * 执行shell
     * @param file 执行文件
     * @param args 参数逗号分割
     * @return
     */
    public static int execute(String file,String[] args) throws IOException, InterruptedException{
        String[] base={"/bin/sh", file};
        String[] cmd = arrAddEnd(base,args);
        log.info("========================================");
        log.info("你要执行的shell文件:{}",file);
        log.info("你要执行的参数:{}",args);
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                //输出日志到控制台，在实际项目中，将日志信息存储到文件或数据库中
                System.out.println(line);
            }

            int exitCode = process.waitFor();
            if(exitCode!=0) {
                log.error("脚本执行结果失败：{}", exitCode);
                log.info("========================================");
            }else{
                log.info("脚本执行结果：成功！" );
                log.info("========================================");
            }
            return exitCode;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}
